/*********************************************************************************
 *      Copyright:  (C) 2024 LiYi<1751425323@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  client.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(19/04/24)
 *         Author:  LiYi <1751425323@qq.com>
 *      ChangeLog:  1, Release initial version on "19/04/24 15:27:24"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <getopt.h>
#include <libgen.h>
#include <time.h>
#include <signal.h>

#include "ds18b20_project.h"
#include "socket_pack.h"
#include "logger.h"
#include "database.h"

#define TABLE_NAME 		  "PackTable"
#define PROG_VERSION      "v1.0.0"

static inline void print_usage(char *progname);

static inline void print_usage(char *progname)
{
	printf("usage: %s [OPTIN].. \n",progname);

	printf(" %s is a socket server program, which used to verify client and echo back string from it\n",progname);
	printf("\nMandatory arguments to long options are mandatory for short options too:\n");
	printf(" -i[server_ip ] socket server ip address\n");
	printf(" -b[daemon ] set program running on background\n");
	printf(" -p[port ]Socket server port address\n");
	printf(" -h[help ] Display this help information\n");
	printf(" -n");
	printf(" -m");
	printf("\nExample: %s -b -p 8900\n", progname);
	return ;
}

int main(int argc,char **argv)
{
	int				serv_port;
	char			*server_ip=NULL;
	int				daemon_run = 0;
	int				opt;
	char			buf[100];
	char 			*logfile = "../obj/socket_client.log";
	int         	loglevel=LOG_LEVEL_INFO;
	int 			logsize = 10;
	int				sample_flag=0;
	int				connect_flag=0;
	float			temp = 0;
	char			post[100]; //封装发送
	int				num;
	int             in_minute;
	int             time_minute;
	time_t          past_time;
	struct          tm *time_info;
	char            timeString[50];
	time_t          currentTime;
	int 			delay_flag=0;
	char            timeString_buf[50];
	int 			number;
	socket_ctx_t	sock;
	char  			*progname = NULL;

	struct option log_options[]= 
	{
		{"daemon",no_argument,NULL,'b'},
		{"server_ip",required_argument,NULL,'i'},
		{"port",required_argument,NULL,'p'},
		{"number",required_argument,NULL,'n'},
		{"minute",required_argument,NULL,'m'},
		{"help",no_argument,NULL,'h'},
		{NULL,0,NULL,0}
	};

	progname = basename(argv[0]);

	while((opt = getopt_long(argc,argv,"bi:p:n:m:h",log_options,NULL)) != -1)
	{
		switch(opt)
		{
			case 'b':
				daemon_run = 1;
				break;
			case 'i':
				server_ip = optarg; 
				break;
			case 'p':
				serv_port = atoi(optarg);
				break;
			case 'n':
				number=atoi(optarg);
				break;
			case 'm':
				in_minute=atoi(optarg);
				break;
			case 'h':
				print_usage(progname);
				return EXIT_SUCCESS;
			default:
				break;
		}
	}
	past_time = time(NULL);
	time_minute = in_minute;

	signal(SIGPIPE,SIG_IGN);

	if(log_open(logfile,loglevel,logsize,THREAD_LOCK_NONE) < 0) 
	{
		fprintf(stderr,"initial log system failed\n");
		return 1;
	}

	if(database_init("../obj/socket_client.db") < 0)
	{
		printf("111");
		log_error("database_init failure: %s\n");
		return -2;
	}
	socket_init(&sock,server_ip,serv_port);
	while(1)
	{

		delay_flag = 0;
		currentTime = time(NULL);
		time_info = localtime(&currentTime);
		strftime(timeString, sizeof(timeString), "%Y-%m-%d-%H:%M:%S", time_info); //转换格式
		if((int)(currentTime - past_time) >= time_minute)
		{
			past_time = currentTime;
			delay_flag = 1;
		}

		memset(timeString_buf,0,sizeof(timeString_buf));

		sample_flag = 0;
		if(delay_flag)
		{
			log_debug("start DS18B20 sample termperature\n");

			if((temp = get_temp()) < 0)
			{
				log_error("DS18B20 sample temperature failure, temperature: %.3f",temp/1000);
				continue;
			}

			log_info("DS18B20 sample temperature: %.3f oC\n",temp/1000);

			sample_flag = 1;
		}
		 sprintf(timeString_buf,"number: %d - temperature: %.2f - time : %s\n ",number,temp/1000,timeString);
		if((sock.fd < 0) && (delay_flag == 1))
		{
			printf("5kk: %s\n",sock.host);
			connect_flag = sock_conncet(&sock);
			printf("3ok %s\n",sock.host);
			if(connect_flag)
			{
			database_query_and_clear(sock.fd);
			}
		}

		if(connect_flag < 0)
		{
			if(sample_flag)
			{
				database_insert(timeString_buf,strlen(timeString_buf));
			}
			continue;
		}

		if(sample_flag)
		{
			log_debug("socket send sample temperature: %.3f\n",temp/1000);
			if((num = socket_write(sock.fd,timeString_buf,strlen(timeString_buf))) <= 0)
			{
				log_warn("socket write failure,save it in database now\n");
				database_insert(timeString_buf,strlen(timeString_buf));
				socket_close(&sock);
				connect_flag = 0;

			}
		}
	}

}

